package cn.afactory.tygz.ui.user;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.harwkin.nb.camera.BaseImgView;
import com.harwkin.nb.camera.CropBuilder;
import com.harwkin.nb.camera.callback.CameraImageListener;
import com.harwkin.nb.camera.options.CameraOptions;
import com.harwkin.nb.camera.pop.CameraPop;
import com.harwkin.nb.camera.pop.CameraPopListener;
import com.harwkin.nb.camera.type.OpenType;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.ViewInjectInfo;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.Calendar;
import java.util.Date;

import cn.afactory.tygz.R;
import cn.afactory.tygz.db.DBManager;
import cn.afactory.tygz.model.Address;
import cn.afactory.tygz.model.UploadFileInfoList;
import cn.afactory.tygz.model.UserInfo;
import cn.afactory.tygz.net.NetManager;
import cn.afactory.tygz.net.lsn.OnResponseListener;
import cn.afactory.tygz.ui.MyTextActivity;
import cn.afactory.tygz.ui.base.BaseActivity;
import cn.afactory.tygz.ui.base.utils.DateUtil;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.base.utils.StringUtils;
import cn.afactory.tygz.ui.common.HomeTownSelectActivity;

/**
 * Created with Android Studio.
 * Title:UserInfoUpdateActivity
 * Description:
 * Copyright:Copyright (c) 2015
 * Company:和平必胜、正义必胜、人民必胜
 * Author:炎黄子孙
 * Date:15/9/15
 * Time:下午2:07
 * Version 1.0
 */
@ContentView(R.layout.ac_user_info_modify)
public class UserInfoUpdateActivity extends BaseActivity implements View.OnClickListener, CameraPopListener,
        CameraImageListener {
    public static final int REQ_TEXT_INPUT = 0x2001;

    public static final int SELECT_TYPE_NICK_NAME = 0x200;
    public static final int SELECT_TYPE_SIGN = 0x201;
    public static final int SELECT_TYPE_INTRO = 0x202;
    public static final int SELECT_TYPE_DEST = 0x203;
    public static final int SELECT_TYPE_COMPANY = 0x204;

    @ViewInject(R.id.rl_user_icon)
    private RelativeLayout rl_user_icon;
    @ViewInject(R.id.rl_user_name)
    private RelativeLayout rl_user_name;
    @ViewInject(R.id.rl_user_birthday)
    private RelativeLayout rl_user_birthday;
    @ViewInject(R.id.rl_user_status)
    private RelativeLayout rl_user_status;
    @ViewInject(R.id.rl_user_sign)
    private RelativeLayout rl_user_sign;
    @ViewInject(R.id.rl_user_goal)
    private RelativeLayout rl_user_goal;
    @ViewInject(R.id.rl_location)
    private RelativeLayout rl_location;
    @ViewInject(R.id.rl_hometown)
    private RelativeLayout rl_hometown;
    @ViewInject(R.id.rl_user_intro)
    private RelativeLayout rl_user_intro;
    @ViewInject(R.id.rl_company)
    private RelativeLayout rl_company;

    @ViewInject(R.id.iv_user_icon)
    private ImageView iv_user_icon;
    @ViewInject(R.id.tv_user_name)
    private TextView tv_user_name;
    @ViewInject(R.id.tv_user_birthday)
    private TextView tv_user_birthday;
    @ViewInject(R.id.tv_user_status)
    private TextView tv_user_status;
    @ViewInject(R.id.tv_user_sign)
    private TextView tv_user_sign;
    @ViewInject(R.id.tv_user_goal)
    private TextView tv_user_goal;
    @ViewInject(R.id.tv_location)
    private TextView tv_location;
    @ViewInject(R.id.tv_hometown)
    private TextView tv_hometown;
    @ViewInject(R.id.tv_user_intro)
    private TextView tv_user_intro;
    @ViewInject(R.id.tv_company)
    private TextView tv_company;


    private UserInfo mUserInfo;
    private String mHeadIconPath = null;
    private CameraPop mCameraPop;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        setTitleText("资料修改");

        mUserInfo = DBManager.getInstance(this).getDefaultUserInfo();

        initViews();
        updateProfile();
        initCamera();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (UserInfoCollectionActivity.REQ_ADD_HOMETOWN_ADDRESS_CODE == requestCode) {
            showAddress(resultCode, data,requestCode);
        } else if (UserInfoCollectionActivity.REQ_ADD_LOCATION_ADDRESS_CODE == requestCode) {
            showAddress(resultCode, data,requestCode);
        } else if(REQ_TEXT_INPUT == requestCode){
            if(resultCode == RESULT_OK){
                String value = data.getStringExtra(SPUtils.EXTRA_SELECT_CURRENT_VALUE);
                int type = data.getIntExtra(SPUtils.EXTRA_SELECT_TYPE,-1);
                if(type == SELECT_TYPE_NICK_NAME){
                    tv_user_name.setText(value);
                    doUpdateProfile(null,
                            value,
                            -1,
                            null,
                            null,
                            -1,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null);
                }else if(type == SELECT_TYPE_SIGN){
                    tv_user_sign.setText(value);
                    doUpdateProfile(null,
                            null,
                            -1,
                            null,
                            null,
                            -1,
                            null,
                            value,
                            null,
                            null,
                            null,
                            null,
                            null);
                }else if(type == SELECT_TYPE_INTRO){
                    tv_user_intro.setText(value);
                    doUpdateProfile(null,
                            null,
                            -1,
                            null,
                            null,
                            -1,
                            null,
                            null,
                            null,
                            null,
                            null,
                            value,
                            null);
                }else if(type == SELECT_TYPE_DEST){
                    tv_user_goal.setText(value);
                    doUpdateProfile(null,
                            null,
                            -1,
                            null,
                            null,
                            -1,
                            null,
                            null,
                            value,
                            null,
                            null,
                            null,
                            null);
                }else if(type == SELECT_TYPE_COMPANY){
                    tv_company.setText(value);
                    doUpdateProfile(null,
                            null,
                            -1,
                            null,
                            null,
                            -1,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            value);
                }
            }
        } else {
            if (mCameraPop != null) {
                mCameraPop.forResult(requestCode, resultCode, data);
            }
        }
    }

    private void initCamera() {
        if (mCameraPop == null) {
            mCameraPop = new CameraPop(this, this,this);
        }
    }

    Address mAddressBean;
    /**
     * 展示城市
     * @param resultCode
     * @param data
     */
    private void showAddress(int resultCode, Intent data,int reqCode) {
        if (resultCode == Activity.RESULT_OK) {
            Address addressCodeName = (Address) data
                    .getSerializableExtra(SPUtils.EXTRA_DATA);
            if (null == mAddressBean) {
                mAddressBean = new Address();
            }
            mAddressBean.city = addressCodeName.city;
            mAddressBean.cityCode = addressCodeName.cityCode;
            mAddressBean.areaCode = addressCodeName.areaCode;
            mAddressBean.area = addressCodeName.area;
            mAddressBean.province = addressCodeName.province;
            mAddressBean.provinceCode = addressCodeName.provinceCode;
            StringBuffer buffer = new StringBuffer();
            showCity(addressCodeName, buffer);
            if(reqCode == UserInfoCollectionActivity.REQ_ADD_HOMETOWN_ADDRESS_CODE) {
                doUpdateProfile(null,
                        null,
                        -1,
                        mAddressBean.cityCode,
                        mAddressBean.city,
                        -1,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null);
//                tv_hometown.setText(buffer.toString());
            }else if(reqCode == UserInfoCollectionActivity.REQ_ADD_LOCATION_ADDRESS_CODE) {
                doUpdateProfile(null,
                        null,
                        -1,
                        null,
                        null,
                        -1,
                        null,
                        null,
                        null,
                        mAddressBean.cityCode,
                        mAddressBean.city,
                        null,
                        null);
//                tv_location.setText(buffer.toString());
            }
        }
    }

    private void showCity(Address addressCodeName, StringBuffer buffer) {
        buffer.append(StringUtils.nullToEmpty(addressCodeName.province));
        buffer.append("  ");
        buffer.append(StringUtils.nullToEmpty(addressCodeName.city));
        if(!StringUtils.isEmpty(addressCodeName.city)){
            buffer.append("  ");
        }
        if(!StringUtils.isEmpty(addressCodeName.area)){
            buffer.append(StringUtils.nullToEmpty(addressCodeName.area));
        }
    }

    private void initViews(){
        rl_user_icon.setOnClickListener(this);
        rl_user_name.setOnClickListener(this);
        rl_user_birthday.setOnClickListener(this);
        rl_user_status.setOnClickListener(this);
        rl_user_sign.setOnClickListener(this);
        rl_user_goal.setOnClickListener(this);
        rl_location.setOnClickListener(this);
        rl_hometown.setOnClickListener(this);
        rl_user_intro.setOnClickListener(this);
        rl_company.setOnClickListener(this);
    }

    private void updateProfile(){
        mUserInfo = DBManager.getInstance(this).getDefaultUserInfo();
        if(mUserInfo.nickName != null){
            tv_user_name.setText(mUserInfo.nickName);
        }else{
            tv_user_name.setText(R.string.label_unknown_select);
        }

        if (mUserInfo.userIcon != null) {
            BaseImgView.loadimg(iv_user_icon,
                    mUserInfo.userIcon,
                    R.drawable.ic_pic_loading_default_small,
                    R.drawable.ic_pic_loading_default_small,
                    R.drawable.ic_pic_loading_default_small, ImageScaleType.EXACTLY,
                    (int) mContext.getResources().getDimension(R.dimen.healthcircle_padding30),
                    (int) mContext.getResources().getDimension(R.dimen.healthcircle_padding30),
                    0);
        } else {
            iv_user_icon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_pic_loading_default_small));
        }

        if(mUserInfo.birth != 0){
            tv_user_birthday.setText(DateUtil.getDisplayDate(mUserInfo.birth, "yyyy-MM"));
        }else{
           tv_user_birthday.setText(R.string.label_unknown_select);
        }

        if(mUserInfo.maritalStatus != null){
            tv_user_status.setText(mUserInfo.maritalStatus);
        }else{
            tv_user_status.setText(R.string.label_unknown_select);
        }

        if(mUserInfo.signature != null){
            tv_user_sign.setText(mUserInfo.signature);
        }else{
            tv_user_sign.setText(R.string.label_unknown_select);
        }

        if(mUserInfo.dest != null){
            tv_user_goal.setText(mUserInfo.dest);
        }else{
            tv_user_goal.setText(R.string.label_unknown_select);
        }

        if(mUserInfo.locationCityName != null){
            tv_location.setText(mUserInfo.locationCityName);
        }else{
            tv_location.setText(R.string.label_unknown_select);
        }

        if(mUserInfo.cityName != null){
            tv_hometown.setText(mUserInfo.cityName);
        }else{
            tv_hometown.setText(R.string.label_unknown_select);
        }

        if(mUserInfo.intro != null){
            tv_user_intro.setText(mUserInfo.intro);
        }else{
            tv_user_intro.setText(R.string.label_unknown_select);
        }

        if(mUserInfo.company != null){
            tv_company.setText(mUserInfo.company);
        }else{
            tv_company.setText(R.string.label_unknown_select);
        }
    }

    public static void gotoUserInfoUpdatePage(Context context){
        context.startActivity(new Intent(context, UserInfoUpdateActivity.class));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_user_icon:
                doPickHeadIcon();
                break;
            case R.id.rl_user_name:
                doPickUserName();
                break;
            case R.id.rl_user_birthday:
                doPickUserBirthday();
                break;
            case R.id.rl_user_status:
                doPickUserStatus();
                break;
            case R.id.rl_user_sign:
                doPickUserSign();
                break;
            case R.id.rl_user_goal:
                doPickUserGoal();
                break;
            case R.id.rl_location:
                doPickUserLocation();
                break;
            case R.id.rl_hometown:
                doPickUserHomeTown();
                break;
            case R.id.rl_user_intro:
                doPickUserIntro();
                break;
            case R.id.rl_company:
                doPickCompany();
                break;
        }
    }

    /**
     * 选择头像
     */
    private void doPickHeadIcon(){
        mCameraPop.showMenu(iv_user_icon);
    }

    /**
     * 选择昵称
     */
    private void doPickUserName(){
        MyTextActivity.gotoSeclectText(this, "昵称", SELECT_TYPE_NICK_NAME, mUserInfo.nickName);
    }

    /**
     * 选择生日
     */
    private void doPickUserBirthday(){
        int year = 1990;
        int month = 1;
        int day = 1;
        if(mUserInfo.birth != 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(mUserInfo.birth);

            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
        }
        DatePickerDialog mDatePickerDialog = new DatePickerDialog(
                this,
                R.style.AppTheme_Dialog,
                new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(year,monthOfYear,dayOfMonth);
                doUpdateProfile(null,
                        null,
                        -1,
                        null,
                        null,
                        calendar.getTimeInMillis(),
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null);
            }
        },year,month,day);
        mDatePickerDialog.show();
    }

    /**
     * 选择情感状态
     */
    private void doPickUserStatus(){
        new AlertDialog.Builder(this,android.R.style.Theme_Holo_Light_Dialog)
                .setTitle("请选择您的情感状态")
                .setItems(R.array.array_user_status, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String userStatus = getResources().getStringArray(R.array.array_user_status)[which];
                        doUpdateProfile(null,
                                null,
                                -1,
                                null,
                                null,
                                -1,
                                userStatus,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null);
                    }
                })
                .create()
                .show();
    }

    /**
     * 选择签名
     */
    private void doPickUserSign(){
       MyTextActivity.gotoSeclectText(this, getString(R.string.title_text_signature), SELECT_TYPE_SIGN, mUserInfo.signature);
    }

    /**
     * 选择目的
     */
    private void doPickUserGoal(){
       MyTextActivity.gotoSeclectText(this,getString(R.string.title_find_goal),SELECT_TYPE_DEST,mUserInfo.dest);
    }

    /**
     * 选择公司
     */
    private void doPickCompany(){
        MyTextActivity.gotoSeclectText(this,getString(R.string.title_edit_company),SELECT_TYPE_COMPANY,mUserInfo.company);
    }


    /**
     * 选择所在地
     */
    private void doPickUserLocation(){
        Address address = new Address();
//        address.cityCode = mUserInfo.locationCity;
        HomeTownSelectActivity.gotoSelectHometown(this, address, UserInfoCollectionActivity.REQ_ADD_LOCATION_ADDRESS_CODE);
    }

    /**
     * 选择用户家乡
     */
    private void doPickUserHomeTown(){
        Address address = new Address();
//        address.cityCode = mUserInfo.city;
        HomeTownSelectActivity.gotoSelectHometown(this, address, UserInfoCollectionActivity.REQ_ADD_HOMETOWN_ADDRESS_CODE);
    }

    /**
     *选择自我介绍
     */
    private void doPickUserIntro(){
        MyTextActivity.gotoSeclectText(this,getString(R.string.title_text_introduction),SELECT_TYPE_INTRO,mUserInfo.intro);
    }

    @Override
    public void onCamreaClick(CameraOptions options) {
        options.setOpenType(OpenType.OPEN_CAMERA_CROP)
                .setCropBuilder(new CropBuilder(1, 1, 300, 300));
        managerProcess();
    }

    @Override
    public void onPickClick(CameraOptions options) {
        options.setOpenType(OpenType.OPEN_GALLERY_CROP)
                .setCropBuilder(new CropBuilder(1, 1, 300, 300));
        managerProcess();
    }

    @Override
    public void onDelClick() {

    }

    /**
     * 执行照片处理
     */
    private void managerProcess() {
        mCameraPop.process();
        if (null != mCameraPop) {
            mCameraPop.dismiss();
        }
    }

    @Override
    public void onSelectedAsy(String imgPath) {
        UpImagefromCut(imgPath);
    }

    /**
     * 更新个人资料
     */
    private void doUpdateProfile(
            final String headIcon,
            final String nickName,
            final int sex,
            final String cityCode,
            final String cityName,
            final long birthday,
            final String userStatus,
            final String sign,
            final String goal,
            final String locationCityCode,
            final String locationCityName,
            final String intro,
            final String company){
        showLoadingView("资料保存中...");
        NetManager.getInstance(this).doUpdateUserInfo(headIcon,
                nickName,
                sex,
                cityCode,
                cityName,
                birthday,
                userStatus,
                sign,
                goal,
                locationCityCode,
                locationCityName,
                intro,
                company,
                new OnResponseListener<UserInfo>() {
                    @Override
                    public void onComplete(boolean isOK, UserInfo result, int errorCode, String errorMsg) {
                        hideLoadingView();
                        if(isOK && result != null){
                            mUserInfo = result;
                            updateProfile();
                        }else{
                            LocalUtils.showToast(UserInfoUpdateActivity.this,errorMsg);
                        }
                    }

                    @Override
                    public void onInternError(int errorCode, String errorMessage) {
                        hideLoadingView();
                        LocalUtils.showToast(UserInfoUpdateActivity.this,errorMessage);
                    }
                });
    }

    protected void UpImagefromCut(String data) {
        if (data == null) {
            return;
        }
        if (data != null && data.length() > 0) {
            UploadImage(data);
        }
    }

    /**
     * 上传头像
     * @param file
     */
    protected void UploadImage(final String file) {
        showLoadingView("头像上传中...");
        NetManager.getInstance(this).doUploadImage(file,
                "1",
                new OnResponseListener<UploadFileInfoList>() {

                    @Override
                    public void onInternError(int errorCode, String errorMessage) {
                        hideLoadingView();
                        LocalUtils.showToast(UserInfoUpdateActivity.this, errorMessage);
                    }

                    @Override
                    public void onComplete(boolean isOK, UploadFileInfoList result, int errorCode, String errorMsg) {
                        hideLoadingView();
                        if (isOK) {
                            if (result != null&& result.data.size() > 0) {
                                mHeadIconPath = String.valueOf(result.data.get(0).fileId);
                                String url = result.data.get(0).url;
                                BaseImgView.loadimg(iv_user_icon, url, R.drawable.ic_pic_loading_default_small,
                                        R.drawable.ic_pic_loading_default_small, R.drawable.ic_pic_loading_default_small, ImageScaleType.EXACTLY,
                                        (int) mContext.getResources().getDimension(R.dimen.margin_45dp),
                                        (int) mContext.getResources().getDimension(R.dimen.margin_45dp),
                                        0);

                                doUpdateProfile(result.data.get(0).fileId + "",
                                        null,
                                        -1,
                                        null,
                                        null,
                                        -1,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null);
                            } else {
                                LocalUtils.showToast(UserInfoUpdateActivity.this, "头像上传失败，请稍候重试");
                            }
                        } else {
                            LocalUtils.showToast(UserInfoUpdateActivity.this,errorMsg);
                        }
                    }
                });
    }
}
